package com.btl.cygf;

import java.util.LinkedList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.btl.bean.ZuiXin;
import com.btl.utils.DownTuUtils;
import com.btl.utils.TimeUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yzx.yunyanzhengdemo.activity.LoginActivity;

public class TieZiPingLunActivity extends Activity implements OnClickListener {

	private PullToRefreshListView mListView;
	private LinkedList<ZuiXin> listItems = new LinkedList<ZuiXin>(); // 数据源集合
	private ArrayAdapter<String> mAdapter;
	private MyListAdapter myListAdapter;
	private AsyncHttpClient client;
	private RequestParams params;
	private int v_id;
	private int c_id;
	private String p_id;
	private int lastid;
	ImageLoader imageLoader = ImageLoader.getInstance();
	SharedPreferences share;

	ImageView login_backtofragment;
	TextView pinglun;
	LinearLayout dibu;

	EditText edit; // 发布的评论
	ImageView fasong; // 点击发送
	
	boolean flog = false;  //这是一个标志

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_fenlei);

		Intent intent = getIntent();
		v_id = Integer.valueOf(intent.getStringExtra("v_id"));

		dibu = (LinearLayout) findViewById(R.id.dibu1);
		dibu.setVisibility(View.VISIBLE);

		edit = (EditText) findViewById(R.id.text);
		fasong = (ImageView) findViewById(R.id.fasong);
		fasong.setOnClickListener(this);
		login_backtofragment = (ImageView) findViewById(R.id.login_backtofragment);
		login_backtofragment.setOnClickListener(this);
		pinglun = (TextView) findViewById(R.id.fenlei_title_txt);
		pinglun.setText("评论");

		edit.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (edit.getText().toString().length() > 0) {
					fasong.setImageResource(R.drawable.send_d);
					flog = true;
				} else {
					fasong.setImageResource(R.drawable.send_u);
					flog = false;
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		share = getSharedPreferences("login", Activity.MODE_WORLD_READABLE);
		p_id = share.getString("id", "");

		/**
		 * 异步加载网络资源信息
		 */
		client = new AsyncHttpClient();
		// 像网络传输的数据
		params = new RequestParams();
		// 链接到网络，获取数据
		getDataRefresh();

		mListView = (PullToRefreshListView) findViewById(R.id.list_zuixin);

		mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(
						getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				// Do work to refresh the list here.
				if (mListView.isHeaderShown()) {
					// 下拉刷新
					getDataRefresh();
				} else if (mListView.isFooterShown()) {
					// 上拉加载
					if (c_id == lastid) {
						mListView.getLoadingLayoutProxy(false, true)
								.setRefreshingLabel("没有更多选项");
						// mListView.setMode(Mode.DISABLED);
						new GetDataTask().execute();
					} else {
						getDataMore(c_id);
					}
				}
			}
		});

		mListView.setMode(Mode.BOTH);
		mListView.getLoadingLayoutProxy(false, true).setPullLabel("加载完成");
		mListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载");
		mListView.getLoadingLayoutProxy(false, true).setReleaseLabel("上拉以加载");
		mListView.getRefreshableView().setAdapter(mAdapter);

		// listItems = getListItems();
		myListAdapter = new MyListAdapter();
		mListView.setAdapter(myListAdapter);

	}

	/**
	 * 连接到网络 获取数据
	 * 
	 * @param pagenow
	 */
	private void getDataRefresh() {
		params.remove("v_id");
		params.add("v_id", v_id + "");
		// 实例LinkList数据源
		listItems = new LinkedList<ZuiXin>();
		// 连接查看分类（刷新）
		client.post(getResources().getString(R.string.url)
				+ "/CYGF/commentRefreshJason.post", params,
				new JsonHttpResponseHandler() {
					// 链接成功做出的反应
					public void onSuccess(int statusCode, Header[] headers,
							JSONArray response) {
						for (int i = 0; i < response.length(); i++) {
							ZuiXin zuiXin = new ZuiXin();
							JSONObject object = response.optJSONObject(i);
							String s2 = object.optString("c_content");
							String s3 = object.optString("c_time");
							String s4 = object.optString("p_id");
							String s5 = object.optString("p_nickname");
							String s6 = object.optString("p_avatar");
							zuiXin.setTouxiang(s6);
							zuiXin.setContent(s2);
							zuiXin.setDatepinlun(TimeUtils.getDate(s3));
							if (s5 == null) {
								zuiXin.setComuser(s4);
							} else {
								zuiXin.setComuser(s5);
							}
							listItems.add(zuiXin);
							// imageLoader.DisplayImage(zuiXin.getPicture(),
							// img);
							// img.setImageResource(R.drawable.advertising_default_1);
							// listItems.addFirst(zuiXin);
						}
						// BaseAdapter数据发生改变
						int i = listItems.size();
						myListAdapter.notifyDataSetChanged();
						mListView.onRefreshComplete();

						super.onSuccess(statusCode, headers, response);
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONObject errorResponse) {
						// TODO Auto-generated method stub
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}

					// 链接网络失败，做出的反应
					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONArray errorResponse) {
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}
				});
	}

	/**
	 * 下拉加载更多
	 */
	private void getDataMore(final int cid) {
		params.remove("c_id");
		params.remove("v_id");
		params.add("c_id", cid + "");
		params.add("v_id", v_id + "");
		// 连接查看分类（加载）
		client.post(getResources().getString(R.string.url)
				+ "/CYGF/commentMoreJason.post", params,
				new JsonHttpResponseHandler() {
					// 链接成功做出的反应
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONArray response) {
						Log.i("vid", cid + "");
						Log.i("vid", lastid + "");
						if (cid == lastid) {
							mListView.getLoadingLayoutProxy(false, true)
									.setRefreshingLabel("没有更多选项");
							// mListView.setMode(Mode.DISABLED);
							new GetDataTask().execute();
						} else {
							for (int i = 0; i < response.length(); i++) {
								ZuiXin zuiXin = new ZuiXin();
								JSONObject object = response.optJSONObject(i);
								String s2 = object.optString("c_content");
								String s3 = object.optString("c_time");
								String s4 = object.optString("p_id");
								String s5 = object.optString("p_nickname");
								String s6 = object.optString("p_avatar");
								zuiXin.setTouxiang(s6);
								zuiXin.setContent(s2);
								zuiXin.setDatepinlun(TimeUtils.getDate(s3));
								if (s5 == null) {
									zuiXin.setComuser(s4);
								} else {
									zuiXin.setComuser(s5);
								}
								listItems.add(zuiXin);
								zuiXin = null;
								if (i == (response.length() - 1)) {
									c_id = Integer.parseInt(object
											.optString("c_id"));
								}
							}
							// BaseAdapter数据发生改变
							myListAdapter.notifyDataSetChanged();
							mListView.onRefreshComplete();

						}

						super.onSuccess(statusCode, headers, response);
					}

					// 链接网络失败，做出的反应
					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONArray errorResponse) {
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}
				});
	}

	/**
	 * listview的适配器MyListAdapter
	 */
	private class MyListAdapter extends BaseAdapter {

		class ListItemView {
			public ImageView image;
			public TextView username;
			public TextView time;
			public TextView comment;
		}

		@Override
		public int getCount() {
			return listItems.size();
		}

		@Override
		public Object getItem(int position) {

			return listItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// final int selectID = position;
			// 自定义视图
			ListItemView listItemView = null;
			if (convertView == null) {
				listItemView = new ListItemView();
				// 获取list_item布局文件的视图
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.pinglun_item_layout, null);
				// 获取控件对象
				listItemView.image = (ImageView) convertView
						.findViewById(R.id.touxiang);
				listItemView.username = (TextView) convertView
						.findViewById(R.id.title);
				listItemView.time = (TextView) convertView
						.findViewById(R.id.time);
				listItemView.comment = (TextView) convertView
						.findViewById(R.id.pinglunneiron);

				// 设置控件集到convertView
				convertView.setTag(listItemView);
			} else {
				listItemView = (ListItemView) convertView.getTag();
			}

			// 设置文字和图片
			// listItemView.image.setImageDrawable(getResources().getDrawable(R.drawable.advertising_default_1));
			// listItemView.image.setImageBitmap(new
			// BitmapFactory().decodeByteArray(data, offset, length))
			System.out.println("评论" + listItems.get(position).getTouxiang());
			imageLoader.displayImage(listItems.get(position).getTouxiang(),
					listItemView.image, DownTuUtils.getOptions2());

			// listItemView.image.setImageResource(R.drawable.advertising_default_1);
			listItemView.username.setText(listItems.get(position).getComuser());
			listItemView.time.setText(listItems.get(position).getDatepinlun());
			listItemView.comment.setText(listItems.get(position).getContent());
			return convertView;
		}
	}

	private class GetDataTask extends AsyncTask<Void, Void, String> {

		// 后台处理部分
		@Override
		protected String doInBackground(Void... params) {
			// Simulates a background job.
			// mListView.getLoadingLayoutProxy(false,
			// true).setRefreshingLabel("没有更多选项");
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
			}
			String str = "Added after refresh...I add";
			return str;
		}

		// 这里是对刷新的响应，可以利用addFirst（）和addLast()函数将新加的内容加到LISTView中
		// 根据AsyncTask的原理，onPostExecute里的result的值就是doInBackground()的返回值
		@Override
		protected void onPostExecute(String result) {

			// 通知程序数据集已经改变，如果不做通知，那么将不会刷新mListItems的集合
			// myListAdapter.notifyDataSetChanged();
			// 32tCall onRefreshComplete when the list has been refreshed.
			mListView.onRefreshComplete();
			super.onPostExecute(result);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {

				Intent it = new Intent(TieZiPingLunActivity.this,
						TieZiActivity.class);
				it.putExtra("v_id", v_id + "");
				it.putExtra("type", "1");

				it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(it);

			}
		}
		return false;
	}

	// 点击返回
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_backtofragment:

			Intent it = new Intent(TieZiPingLunActivity.this,
					TieZiActivity.class);
			it.putExtra("v_id", v_id + "");
			it.putExtra("type", "1");

			it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(it);
			break;

		case R.id.fasong:

			if (flog) {
				if (!p_id.equals("")) {
					params.remove("p_id");
					params.add("p_id", p_id);
					params.remove("v_id");
					params.add("v_id", v_id + "");
					params.remove("c_content");
					params.add("c_content", edit.getText().toString());
					client.post(getResources().getString(R.string.url)
							+ "/CYGF/commentsend.post", params,
							new JsonHttpResponseHandler() {

								@Override
								public void onSuccess(int statusCode,
										Header[] headers, JSONArray response) {
									JSONObject object = response.optJSONObject(0);
									if ("评论成功".equals(object.optString("msg"))) {
										getDataRefresh();
									}
								}
							});

					edit.setText("");
					InputMethodManager imm = (InputMethodManager)getSystemService(TieZiPingLunActivity.this.INPUT_METHOD_SERVICE);  
					imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);


				} else {
					Intent it2 = new Intent();
					it2.setClass(TieZiPingLunActivity.this, LoginActivity.class);
					startActivity(it2);
				}

			}
			else {
				//不做处理
			}
			
		}
	}
}
